<!-- eslint-disable prettier/prettier -->
<template>
  <div class="about">
    <div class="labelbox">
      <span class="timeout1">考试时间：{{ timeOutM }}:{{ timeOutS }}</span>
    </div>
    <el-dialog
      title="温馨提示"
      :visible.sync="dialogVisible"
      width="30%">
      <span>考试时间30分钟，请认真答题，倒计时结束自动交卷。</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onComfirm">确 定</el-button>
      </span>
    </el-dialog>
    <div class="content_box" v-loading="comLoading">
      <div class="topic_item" v-for="(item, $index) in topicList" :key="$index">
        <div class="serial">{{ $index+1 }}.</div>
        <div class="topic_content">
          <dan-xuan
            v-if="item.type == 'select'"
            :disable="testEnd"
            :labelText="item.question"
            :options="item.options"
            :img="item.img"
            @changeSelect="($emit) => changeSelect($emit, $index)">
          </dan-xuan>
          <pan-duan
            v-if="item.type == 'torf'"
            :disable="testEnd"
            :labelText="item.question"
            :img="item.img"
            @changeSelect="($emit) => changeSelect($emit, $index)">
          </pan-duan>
          <my-input
            v-if="item.type == 'textarea'"
            :disable="testEnd"
            :targetContent="item.question"
            @changeInput="($emit) => changeInput($emit, $index)">
          </my-input>
          <div v-if="showRequired[$index]" class="error_tips" style="font-size:14px">请作答</div>
        </div>
        <div class="real_answer" v-if="testEnd">
          <span class="result_box answer_right" v-if="item.type != 'textarea' && item.getScore == item.score">正确</span>
          <span class="result_box error_tips" v-if="item.type != 'textarea' && item.getScore != item.score">{{ item.feedBack }}</span>
          <span class="result_box answer_right" v-if="item.type == 'textarea'">正确率：{{ item.getScore }}%</span>
        </div>
      </div>
    </div>
    <div class="submit_box">
      <el-button type="primary" v-if="!testEnd" plain @click="submitForm">提 交</el-button>
      <span class="bottom_score" v-if="testEnd">总分：{{ fullScore }}&nbsp;&nbsp;&nbsp;&nbsp;得分：{{ result }}</span>
    </div>
  </div>
</template>
<script>
// @ is an alias to /src
// import HelloWorld from "@/components/HelloWorld.vue";
/**
 * 得分根据是否合格显示颜色 字体加大
 */
import MyInput from "@/components/wenziluru.vue"
import PanDuan from "@/components/panduan.vue"
import DanXuan from "@/components/danxuan.vue"
// import { topicData } from "@/components/topic1.js" // 测试数据
export default {
  name: "Home",
  components: {
    // HelloWorld,
    MyInput,
    PanDuan,
    DanXuan
  },
  data() {
    return {
      dialogVisible: true,  // 温馨提示框开关
      timeOutM: "30",  // 倒计时时间-分 默认5分钟
      timeOutS: "00",  // 倒计时时间-秒
      timeOver: false, // 是否时间结束
      topicList: [], // 题目列表
      originForm: {}, // el-form绑定的表单
      rules: {}, // 表单验证规则
      showRequired: [], // 必填验证
      comLoading: false, // 页面加载效果
      testEnd: false, // 已交卷
      result: 0,
      fullScore: 0 // 总分
    }
  },
  methods: {
    // 弹窗确认，开始考试
    onComfirm() {
      this.dialogVisible = false
      this.timeReset()
    },
    // 计时
    timeReset() {
      let m = Number(this.timeOutM)
      let s = Number(this.timeOutS)
      if(this.timeOver) return
      setTimeout(() => {
        if(m == 0 && s == 0){
          this.calculate()
          this.timeOver = true
        }
        else if(s == 0){
          this.timeOutM = String(m - 1);
          this.timeOutS = "59"
        }
        else {
          s -= 1;
          this.timeOutS = s < 10 ? "0" + String(s) : String(s)
        }
        this.timeReset()
      }, 1000);
    },
    // 提交按钮 确认弹窗
    submit() {
      this.$confirm('请仔细检查，交卷后无法更改，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.calculate()
      }).catch(() => {
      });
    },
    // 文字录入内容输入
    changeInput(val,idx) {
      this.originForm[idx]=val
      this.showRequired[idx] = false
    },
    // 选择、判断改动
    changeSelect(val, idx) {
      this.originForm[idx] = val
      this.showRequired[idx] = false
    },
    // 交卷事件，计算得分
    calculate() {
      this.timeOver = true
      this.comLoading = true
      this.result = 0;
      const optLabel = ["A","B","C","D"];
      this.$message({
        message: "正在计算，请稍等",
        type: 'warning'
      })
      console.log(this.originForm)
      this.topicList.forEach((item, index)=> {
        if(item.type == "select" || item.type == "torf") {
          item.getScore = this.originForm[index] == item.answer ? item.score : 0
          if(this.originForm[index] == item.answer) {
            item.getScore = item.score
          } else {
            item.getScore = 0;
            if (item.type == "select") {
              item.feedBack = "正确答案：" + optLabel[item.answer];
            } else {
              item.feedBack = "回答错误";
            }
          }
          this.result += item.getScore;
        } else if(item.type == 'textarea') {
          let res = Number(this.similar(this.originForm[index], item.question))
          item.getScore = (res * 100).toFixed(2);
          this.result += Math.round(res * item.score * 100) / 100;
          console.log('res => ', res, typeof(res), res * item.score, this.result)
        }
      })
      console.log("res score", this.topicList)
      // this.result = eval(this.topicList.map(item => item.getScore).join('+'));
      this.$alert('最终得分：'+this.result , '考试结束', {
        confirmButtonText: '确定',
        callback: () => {
          this.testEnd = true;
        }
        });
      this.comLoading = false
      console.log('show require ', this.showRequired)
    },
    // 提交按钮 判断是否有空题
    submitForm() {
      console.log('originForm', this.originForm)
      let msg = []
      Object.keys(this.originForm).forEach(item => {
        if(this.originForm[item] == null){
          this.showRequired[item] = true
          msg.push(Number(item)+1)
        }
      })
      if(this.showRequired.some(item => item == true)) {
        this.$message({
          message: msg.join(',')+"题还未作答！"
        })
      } else {
        this.submit()
      }
    },
    // 对比字符串相似程度
    similar(s, t) {
      if (!s || !t) {
        return 0
      }
      let l = s.length > t.length ? s.length : t.length
      let n = s.length
      let m = t.length
      let d = []
      let min = function(a, b, c) {
        return a < b ? (a < c ? a : c) : (b < c ? b : c)
      }
      let i, j, si, tj, cost
      if (n === 0) return m
      if (m === 0) return n
      for (i = 0; i <= n; i++) {
        d[i] = []
        d[i][0] = i
      }
      for (j = 0; j <= m; j++) {
        d[0][j] = j
      }
      for (i = 1; i <= n; i++) {
        si = s.charAt(i - 1)
        for (j = 1; j <= m; j++) {
          tj = t.charAt(j - 1)
          if (si === tj) {
            cost = 0
          } else {
            cost = 1
          }
          d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
        }
      }
      let res = (1 - d[n][m] / l)
      return res.toFixed(4);
    },
    // 阻止复制事件
    handleCopy(event) {
      event.preventDefault();
      event.clipboardData.setData('text/plain', '');
    },
    // 阻止右键菜单
    disableRightClick(event) {
      event.preventDefault();
    }
  },
  mounted() {
    // this.timeReset();
    this.comLoading = true;
    this.topicList = [];
    this.fullScore = 0;
    let testContent = JSON.parse(sessionStorage.getItem("testContent"))
    testContent.forEach(item => {
      if(item.code) {
        item.answer = Number(item.code.split('')[9])
      }
      if(item.type == "select") {
        item.options = [item.optionA,item.optionB,item.optionC,item.optionD]
      }
      this.fullScore += item.score
      this.topicList.push(item)
    })
    console.log("mounted topicList => ", this.topicList)
    document.addEventListener('copy', this.handleCopy);
    document.addEventListener('contextmenu', this.disableRightClick);
    this.topicList.forEach((itme, index) => {
      // this.rules[String(index)]=[{ required: true, message: "请作答", trigger: 'blur' }]
      this.originForm[index] = null;
      this.showRequired[index] = false
    })
    this.comLoading = false;
  },
  beforeDestroy() {
    document.removeEventListener('copy', this.handleCopy);
    document.removeEventListener('contextmenu', this.disableRightClick);
  },
};
</script>
<style lang="less" scoped>
.about {
  padding: 0 20px 50px 20px;
  .timeout1 {
    height: 50px;
    line-height: 50px;
    text-align: left;
    position: fixed;
    right: 0;
    top: 0;
    left: 0;
    z-index: 300;
    font-size: 20px;
    font-weight: bolder;
    text-align: right;
    padding: 0 20px;
    // border-bottom: 1px solid #eee;
    color: #333;
    // display: flex;
    // justify-content: space-between;
    .label_title {
      flex: 1
    }
    // .timeout1 {
    //   width: 165px;
    //   font-size: 20px;
    // }
  }
  .topic_item {
    display: flex;
    padding: 10px 20px;
    font-size: 20px;
    border-bottom: 1px solid #f5f5f5;
    justify-content: flex-start;
    .serial{
      width: 30px;
    }
    .topic_content{
      flex: 1;
      max-width: 820px;
    }
    .real_answer{
      width: 180px;
    }
    .item_image {
      max-height: 180px;
      max-width: 240px;
    }
  }
  .submit_box{
    margin-top: 10px;
    text-align: center;
  }
  .demo_ruleForm{
    max-width: 820px;
  }
  .answer_right {
    color: #67C23A
  }
  .result_box {
    font-size: 20px;
    padding-left: 20px
  }
  .error_tips {
    color: #f56c6c;
  }
  .bottom_score {
    margin-left: 30px;
    font-size: 24px;
    font-weight: bold;
  }
  .content_box {
    margin: 0 auto;
  }
}
* {
  -webkit-user-select: none; /* 针对 WebKit 内核的浏览器 */
  -moz-user-select: none; /* 针对 Firefox 浏览器 */
  -ms-user-select: none; /* 针对 IE 浏览器 */
  user-select: none; /* 标准属性 */
}
</style>
